package com.czy.daishusys.ui.order;

import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.daishusys.R;
import com.czy.daishusys.adapter.DeliverGoodsAdapter;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.entity.DeliverGoodsBean;
import com.czy.daishusys.entity.DeliverGoodsModel;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.BaseActivity;
import com.czy.daishusys.utils.GsonUtils;
import com.czy.daishusys.utils.JsonUtil;
import com.czy.daishusys.utils.MyLog;
import com.czy.daishusys.utils.PhoneUtils;
import com.czy.daishusys.widget.MyRecyclerView;
import com.google.gson.Gson;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class DeliverGoodsActivity extends BaseActivity {
    //发货跳转TYPE
    private static final int DETAIL_DELIVER_TYPE = 0x11;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.tv_deliver_sure)
    TextView tvDeliverSure;
    @BindView(R.id.tv_consignee_name)
    TextView tvConsigneeName;
    @BindView(R.id.tv_consignee_phone)
    TextView tvConsigneePhone;
    @BindView(R.id.tv_consignee_address)
    TextView tvConsigneeAddress;
    @BindView(R.id.tv_buyer_tips)
    TextView tvBuyerTips;
    @BindView(R.id.ll_buyer_tips)
    LinearLayout llBuyerTips;
    @BindView(R.id.rv_deliver_goods_info)
    MyRecyclerView rvDeliverGoodsInfo;
    private DeliverGoodsModel.DataBean model;
    private DeliverGoodsAdapter deliverGoodsAdapter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_deliver_goods;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        toolbarTitle.setText("发货");
        EventBus.getDefault().register(this);
        deliverGoodsAdapter = new DeliverGoodsAdapter(R.layout.item_deliver_goods_recycler, new ArrayList<DeliverGoodsModel.DataBean.UListBean>());
        rvDeliverGoodsInfo.setLayoutManager(new LinearLayoutManager(this));
        rvDeliverGoodsInfo.setNestedScrollingEnabled(false);
        rvDeliverGoodsInfo.setAdapter(deliverGoodsAdapter);

        getDeliverOrderInfo();

    }

    private void getDeliverOrderInfo() {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.put("orderId", getIntent().getIntExtra("orderId", 0) + "");
        params.put("pid",UserHelper.getInstance().getDevicePid());
        EasyHttp.post(Constants.SYS_ORDER_DELIVER_DETAIL).params(params).execute(new SimpleCallBack<String>() {
            @Override
            public void onError(ApiException e) {
                mMProgressDialog.dismiss();
                PhoneUtils.ShowToastMessage(DeliverGoodsActivity.this, e.getMessage());
            }

            @Override
            public void onCompleted() {
                super.onCompleted();
                mMProgressDialog.dismiss();
            }

            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                if (flag) {
                    model = GsonUtils.fromJson(result, DeliverGoodsModel.class).getData();
                    tvConsigneeName.setText("收货人: " + model.getShippingAddressName());
                    tvConsigneePhone.setText(model.getShippingAddressContact());
                    tvConsigneeAddress.setText("收货地址: " + model.getShippingAddress());
                    if (TextUtils.isEmpty(model.getNote())) {
                        llBuyerTips.setVisibility(View.GONE);
                    } else {
                        tvBuyerTips.setText("买家备注:" + model.getNote());
                    }
                    for (int i = 0; i < model.getUList().size(); i++) {
                        if (model.getUList().get(i).getAddressList() != null && model.getUList().get(i).getAddressList().size() > 0) {
                            model.getUList().get(i).getAddressList().get(0).setAddressChecked(true);
                        }
                        if (model.getUList().get(i).getDeliveryWayList() != null && model.getUList().get(i).getDeliveryWayList().size() > 0) {
                            model.getUList().get(i).getDeliveryWayList().get(0).setDeliverWayCheck(true);
                        }
                    }

                    deliverGoodsAdapter.setNewData(model.getUList());
                } else {
                    PhoneUtils.ShowToastMessage(DeliverGoodsActivity.this, exp);
                }
            }
        });


    }

    @Override
    protected void updateViews() {

    }

    @Subscribe
    public void onEventMainThread(DeliverGoodsEvent event) {

        if ("address".equals(event.getmMsg())) {
            for (int i = 0; i < model.getUList().get(event.getAdapterPosition()).getAddressList().size(); i++) {
                if (i == event.getClickPosition()) {
                    model.getUList().get(event.getAdapterPosition()).getAddressList().get(i).setAddressChecked(true);
                } else {
                    model.getUList().get(event.getAdapterPosition()).getAddressList().get(i).setAddressChecked(false);
                }
            }
            deliverGoodsAdapter.notifyDataSetChanged();
        } else if ("logistics".equals(event.getmMsg())) {
            for (int i = 0; i < model.getUList().get(event.getAdapterPosition()).getDeliveryWayList().size(); i++) {
                if (i == event.getClickPosition()) {
                    model.getUList().get(event.getAdapterPosition()).getDeliveryWayList().get(i).setDeliverWayCheck(true);
                } else {
                    model.getUList().get(event.getAdapterPosition()).getDeliveryWayList().get(i).setDeliverWayCheck(false);
                }
            }
            deliverGoodsAdapter.notifyDataSetChanged();

        } else if ("goods".equals(event.getmMsg())) {
            model.getUList().get(event.getAdapterPosition()).getOrderItems().get(event.getClickPosition()).setGoodsChecked(event.isChecked());
            deliverGoodsAdapter.notifyDataSetChanged();
        } else if ("contact".equals(event.getmMsg())) {

            model.getUList().get(event.getAdapterPosition()).setLogisticsContact(event.getInputString());

        } else if ("number".equals(event.getmMsg())) {

            model.getUList().get(event.getAdapterPosition()).setLogisticsNumber(event.getInputString());

        } else if ("name".equals(event.getmMsg())) {

            model.getUList().get(event.getAdapterPosition()).setLogisticsName(event.getInputString());

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @OnClick(R.id.tv_deliver_sure)
    public void onViewClicked() {

        DeliverRequest();
    }


    private void DeliverRequest() {

        HttpParams params = new HttpParams();
        params.put("session", UserHelper.getInstance().getSessionInfoModel(DeliverGoodsActivity.this).getSession());
        params.put("orderId", getIntent().getIntExtra("orderId", 0) + "");
        params.put("pid",UserHelper.getInstance().getDevicePid());
        boolean isParamCompleted = true;
        int count=0;
        for (int i = 0; i < model.getUList().size() && isParamCompleted; i++) {
            count+=model.getUList().get(i).getOrderItems().size();
            for (int j = 0; j < model.getUList().get(i).getOrderItems().size(); j++) {
                if (model.getUList().get(i).getOrderItems().get(j).isGoodsChecked()) {
                    if (TextUtils.isEmpty(model.getUList().get(i).getLogisticsName()) || TextUtils.isEmpty(model.getUList().get(i).getLogisticsNumber())||TextUtils.isEmpty(model.getUList().get(i).getLogisticsContact())) {
                        isParamCompleted = false;
                        break;
                    }
                }
            }
        }
        if (!isParamCompleted) {
            PhoneUtils.ShowToastMessage(this, "请完善物流信息!");
            return;
        }
        if (count==0) {
            PhoneUtils.ShowToastMessage(this, "无可发货商品!");
            return;
        }

        List<DeliverGoodsBean> deliverGoodsBeanList = new ArrayList<>();
        boolean isGoodsSelectRight = true;
        for (int i = 0; i < model.getUList().size() && isGoodsSelectRight; i++) {
            DeliverGoodsBean goodsBean = new DeliverGoodsBean();
            StringBuilder stringBuilder = new StringBuilder();
            for (int j = 0; j < model.getUList().get(i).getOrderItems().size(); j++) {
                if (model.getUList().get(i).getOrderItems().get(j).isGoodsChecked()) {
                    if (j + 1 == model.getUList().get(i).getOrderItems().size()) {
                        stringBuilder.append(model.getUList().get(i).getOrderItems().get(j).getOrderItemId() + "");
                    } else {
                        stringBuilder.append(model.getUList().get(i).getOrderItems().get(j).getOrderItemId() + ",");
                    }

                }
            }
            int shipAddressId = 0;
            for (int j = 0; j < model.getUList().get(i).getAddressList().size(); j++) {
                if (model.getUList().get(i).getAddressList().get(j).isAddressChecked()) {
                    shipAddressId = model.getUList().get(i).getAddressList().get(j).getShipAddressId();
                }
            }
            int deliverWayId = 0;
            for (int j = 0; j < model.getUList().get(i).getDeliveryWayList().size(); j++) {
                if (model.getUList().get(i).getDeliveryWayList().get(j).isDeliverWayCheck()) {
                    deliverWayId = model.getUList().get(i).getDeliveryWayList().get(j).getDeliveryWayId();
                }
            }
            if (!TextUtils.isEmpty(stringBuilder)) {
                if ((stringBuilder + "").split(",").length != model.getUList().get(i).getOrderItems().size()) {
                    isGoodsSelectRight = false;
                }
                goodsBean.setIds(stringBuilder + "");
                goodsBean.setShipAddressId(shipAddressId + "");
                goodsBean.setDeliveryWayId(deliverWayId + "");
                goodsBean.setLogisticsContact(model.getUList().get(i).getLogisticsContact() + "");
                goodsBean.setLogisticsNumber(model.getUList().get(i).getLogisticsNumber() + "");
                goodsBean.setLogisticsName(model.getUList().get(i).getLogisticsName() + "");
                deliverGoodsBeanList.add(goodsBean);
            }
        }
        params.put("json", new Gson().toJson(deliverGoodsBeanList));
        MyLog.e("params",params+"");
        mMProgressDialog.show("发货中...");
        EasyHttp.post(Constants.SYS_ORDER_DELIVER).params(params).execute(new SimpleCallBack<String>() {
            @Override
            public void onError(ApiException e) {
                PhoneUtils.ShowToastMessage(DeliverGoodsActivity.this, e.getMessage());
            }

            @Override
            public void onCompleted() {
                super.onCompleted();
                mMProgressDialog.dismiss();
            }

            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                if (flag) {
                    if (getIntent().getIntExtra("type", 0) == DETAIL_DELIVER_TYPE) {
                        setResult(RESULT_OK);
                    }
                    EventBus.getDefault().post(new DeliverGoodsEvent("refresh", 0, 0, "", false));
                    PhoneUtils.ShowToastMessage(DeliverGoodsActivity.this, "发货成功!");
                    finish();
                } else {
                    PhoneUtils.ShowToastMessage(DeliverGoodsActivity.this, exp);
                }
            }
        });


    }


}
